package com.projects.android.adapters;

import java.util.List;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.projects.android.R;
import com.projects.android.dto.FoodDTO;
import com.projects.android.utils.ImageDownloader;
import com.projects.android.utils.SelectedItems;
import com.projects.android.utils.Utils;
import com.projects.android.views.Cart;
import com.projects.android.views.Menu;

public class FoodsAdapter extends ArrayAdapter<FoodDTO> {
	private LayoutInflater mInflater;
	private Context ctx;
	private final ImageDownloader imageDownloader = new ImageDownloader();

	public FoodsAdapter(Context context, int resource, int textViewResourceId,
			List<FoodDTO> objects) {
		super(context, resource, textViewResourceId, objects);
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		ctx = context;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		FoodViewHolder holder = null;
		TextView title = null;
		TextView detail = null;
		ImageView i11 = null;
		ImageButton imgBuy = null;
		
		FoodDTO rowData = getItem(position);

		if (null == convertView) {
			convertView = mInflater.inflate(R.layout.fooditem, null);
			holder = new FoodViewHolder(convertView);
			convertView.setTag(holder);
		}

		holder = (FoodViewHolder) convertView.getTag();

		title = holder.gettitle();
		title.setText(rowData.getName());

		detail = holder.getdetail();
		detail.setText(rowData.getMenuName() + " - " + rowData.getPrice());

		i11 = holder.getImage();
		
		int startPoint = Utils.SERVICE_URI.indexOf('.');
		int startDeli = Utils.SERVICE_URI.indexOf('/', startPoint);
		String webUrl = Utils.SERVICE_URI.substring(0, startDeli); 
		String imgUrl = webUrl + "/Content/Images/" + rowData.getImage();
		Log.i("Image URL", imgUrl);
		imageDownloader.download(imgUrl, i11);

		imgBuy = holder.getImgBuy();
		imgBuy.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				FoodDTO selectedFood = SelectedItems.AllFoods.get(position);
				SelectedItems.SelectedFoods.add(selectedFood);
				
				Toast.makeText(ctx,
						"You have selected '" + selectedFood.getName() + "'",
						Toast.LENGTH_SHORT).show();
				
				// Removew item at selected index
				SelectedItems.AllFoods.remove(selectedFood);
				Menu.MenuView.loadData();
				
				if(Cart.btnCheckOut != null){
					Cart.btnCheckOut.setEnabled(true);
				}
			}
		});
		return convertView;
	}
}
